// pages/posters/posters.js 
import regeneratorRuntime from '../../utils/runtime.js';
import { get } from '../../utils/Helpers';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    poster_url: '',    //海报图片
    vw: '',          //可使用窗口宽度
    vh: '',          //可使用窗口高度
    sh: '',          //屏幕高度
    pixelRatio: '',  //设备像素比
    ctxWidth: '',    //画布宽度
    ctxHeight: '',   //画布高度
    posters: '',     //海报本地地址
    postersHeight: '',    //海报高度
    qrCode: '',    //二维码
    qrCode_url: '',    //二维码
    text:'哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈和哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈和哈哈哈哈哈哈哈哈哈和',
    username:'',
    logo:'',
    position:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    var id = options.id
    wx.request({
      url: app.siteinfo.rootpath + 'gethk_over',
      data: { id: id },
      success: function (res) {
        if (res.data.code == 200) {
          var content = res.data.info.zhufu.replace('@#$', " ");
          that.setData({
            poster_url: res.data.info.bgimg,
            text: '',
            qrCode_url: res.data.info.qrcode,
            username: res.data.info.username,
            logo: res.data.info.logo,
            position: res.data.info.position,
          },()=>{
            console.log(that.data.poster_url)
            console.log(that.data.text)
            console.log(that.data.qrCode_url)
            that.getCanvasData();
          })
        }
      }
    })
    
  },
  getCanvasData: async function () {
    let that = this
    let { qrCode, poster_url, vw, vh, sh, pixelRatio, ctxWidth, ctxHeight, posters, postersHeight, text, qrCode_url} = that.data
    wx.showLoading({
      title: '正在努力生成中...',
    })
    //获取设备信息
    wx.getSystemInfo({
      success: async function (res) {
        await new Promise((resolve, reject) => {
          that.setData({
            vw: res.windowWidth,         //可使用窗口宽度
            vh: res.screenHeight,        //可使用屏幕高度
            sh: res.screenHeight,        //屏幕高度
            pixelRatio: res.pixelRatio,  //设备像素比
            ctxWidth: res.windowWidth * 9 / 10,    //画布宽度=屏幕宽度*90%
          }, () => {
            resolve(true)
          })
        })

        // 获取海报宽高
        await new Promise((resolve) => {
          console.log(poster_url)
          wx.getImageInfo({
            src: poster_url ? poster_url : '',
            success: function (res) {
              let postersHeightnew = res.height * that.data.ctxWidth / res.width;
              that.setData({
                posters: res.path,
                postersHeight: postersHeightnew,
                ctxHeight: postersHeightnew,
              }, () => {
                resolve(true)
              })
            },
            fail: function (e) {
              wx.hideLoading();
              wx.showToast({
                title: e.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        })
        await new Promise((resolve) => {
          console.log(qrCode_url)
          wx.getImageInfo({
            src: qrCode_url ? qrCode_url : '',
            success: function (res) {
              console.log('sss')
              qrCode = res.path
              that.setData({
                qrCode: res.path,  
              }, () => {
                resolve(true)
              })
            },
            fail: function (e) {
              console.log('ddd') 
              wx.hideLoading();
              wx.showToast({
                title: e.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        })
        wx.hideLoading()
        const ctx = wx.createCanvasContext('main')
        const vw = that.data.vw;
        const sh = that.data.sh;
        const ctxWidth = that.data.ctxWidth;
        const ctxHeight = that.data.ctxHeight;
        const postersHeight = that.data.postersHeight
        const posters = that.data.posters;
        console.log('vw', that.data.vw) 
        console.log('sh', that.data.sh)
        console.log('ctxWidth', that.data.ctxWidth)
        console.log('ctxHeight', that.data.ctxHeight)
        console.log('postersHeight', that.data.postersHeight)
        console.log('posters', that.data.posters)
        console.log('qrCode', that.data.qrCode)

        // 画背景色
        ctx.save()
        ctx.beginPath()
        ctx.setFillStyle('#fff')
        ctx.fillRect(0, 0, ctxWidth, ctxHeight)
        ctx.restore()

        // posters
        ctx.beginPath()
        ctx.drawImage(posters, 0, 0, ctxWidth, postersHeight);
        ctx.restore()

        // 二维码
        ctx.beginPath(); 
        ctx.drawImage(qrCode, 20, ctxHeight - 130, 65, 65);
        // ctx.drawImage(code, ctxWidth - 100, ctxHeight - 95, 70, 70);

        // 文字介绍
        ctx.beginPath()
        ctx.setFillStyle('#000000')
        ctx.setFontSize(15)
        ctx.setTextAlign('left')
        ctx.fillText("长按识别", 22, ctxHeight - 42)
        ctx.fillText("进入查看", 22, ctxHeight - 22)
        ctx.setFillStyle('#ffffff')
        ctx.setFontSize(14)
        // ctx.fillText("祝您新年快乐", 22, ctxHeight - 200)
        // ctx.fillText("平平安安猪年大吉", 22, ctxHeight - 160)
        // that.drawText(ctx, text, 45, 220, 200, 200);
        ctx.draw(false, function (e) {
          wx.canvasToTempFilePath({ 

          })
        })
      }
    })
  },


  //文本换行 参数：1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5文本的高度、6、文本的宽度
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 16; //16为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
  },

  downloadImg: function () {
    var that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0.,
      width: that.data.ctxWidth,
      height: that.data.ctxHeight,
      destWidth: that.data.ctxWidth * that.data.pixelRatio,
      destHeight: that.data.ctxHeight * that.data.pixelRatio,
      canvasId: 'main',
      success: function (res) {
        console.log(res.tempFilePath)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})